package com.fly.core;

import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.fly.common.NamedSqlExecutor;
import com.mool.xsqlbuilder.SafeSqlProcesser;
import com.mool.xsqlbuilder.SafeSqlProcesserFactory;
import com.mool.xsqlbuilder.XsqlBuilder;
import com.mool.xsqlbuilder.XsqlBuilder.XsqlFilterResult;

/**
 * 
 * xsqlbuilder封装的动态SQL模板类
 * 
 * @author 00fly
 * @version [版本号, 2018年11月14日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Component
@SuppressWarnings("unchecked")
public class XsqlBuilderSQLTemplate
{
    private static final Logger logger = LoggerFactory.getLogger(XsqlBuilderSQLTemplate.class);
    
    private static XsqlBuilder builder;
    
    @Autowired
    NamedSqlExecutor namedSqlExecute;
    
    static
    {
        // 开启Sql安全过滤
        SafeSqlProcesser safeSqlProcesser = SafeSqlProcesserFactory.getMysql();
        builder = new XsqlBuilder(safeSqlProcesser);
    }
    
    /**
     * 执行查询
     * 
     * @param dynSql xsqlbuilder封装的动态SQL语法语句,e.g: /~ and id= {id} ~/
     * @param params map参数
     * @return
     * @see [类、类#方法、类#成员]
     */
    public List<Map<String, Object>> queryForList(String dynSql, Map<String, Object> params)
    {
        // DynSQL -> namedParamSQL
        XsqlFilterResult result = builder.generateHql(dynSql, params);
        Map<String, Object> filters = result.getAcceptedFilters();
        String namedParamSQL = result.getXsql();
        
        // 处理后的namedParamSQL相关信息
        logger.info("★★★★ processed: params = {}", filters);
        logger.info("★★★★ processed: namedParamSQL = {}", namedParamSQL);
        
        // 执行namedParamSQL查询
        return namedSqlExecute.queryForList(namedParamSQL, filters);
    }
}
